package io.github.talelin.latticy.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * @author tanrentao
 * @since 2021-08-10
 * @decs 自定义验证注解
 */
public class EnumValidator implements ConstraintValidator<Enum, Object> {

    private Class<?> cls;
    private boolean allowNull;

    public EnumValidator() {}

    @Override
    public void initialize(Enum constraintAnnotation) {
        this.cls = constraintAnnotation.target();
        this.allowNull = constraintAnnotation.allowNull();
    }

    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null && this.allowNull) {
            return true;
        } else if (this.cls.isEnum()) {
            Object[] objs = this.cls.getEnumConstants();

            try {
                Method method = this.cls.getMethod("getValue");
                Object[] var5 = objs;
                int var6 = objs.length;

                for(int var7 = 0; var7 < var6; ++var7) {
                    Object obj = var5[var7];
                    Object val = method.invoke(obj);
                    if (val.equals(value)) {
                        return true;
                    }
                }

                return false;
            } catch (Exception var10) {
                return false;
            }
        } else {
            return false;
        }
    }
}
